package com.ndk.push;

import androidx.appcompat.app.AppCompatActivity;

import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;

import com.ndk.push.util.PermissionUtil;
import com.ndk.push.view.DialogManager;

public class MainActivity extends AppCompatActivity {

    private NdkPusher mNdkPusher;
    private SurfaceHolder mSurfaceHolder;
    private boolean isBind = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initPermission();
    }

    private void initView() {
        SurfaceView surfaceView = findViewById(R.id.surfaceView);
        mSurfaceHolder = surfaceView.getHolder();
        mNdkPusher = new NdkPusher(this, Camera.CameraInfo.CAMERA_FACING_BACK, 640, 480, 25, 800000);
    }

    private boolean initPermission() {
        // 判断是否需要动态申请相机权限
        if (!PermissionUtil.checksCameraPermission(this)) {
            DialogManager.getInstance().showDialog(getString(R.string.camera_tip), this, () ->
                    PermissionUtil.requestCameraPermission(this));
            return false;
        }
        // 判断是否需要动态申请麦克风权限
        if (!PermissionUtil.checksRecordAudioPermission(this)) {
            DialogManager.getInstance().showDialog(getString(R.string.recorder_tip), this, () ->
                    PermissionUtil.requestRecordAudioPermission(this));
            return false;
        }
        // 已授权
        return true;
    }

    /**
     * 切换摄像头
     *
     * @param view
     */
    public void switchCamera(View view) {
        if (initPermission()) {
            if (!isBind) {
                mNdkPusher.setPreviewDisplay(mSurfaceHolder);
                isBind = true;
            }
            mNdkPusher.switchCamera();
        }
    }

    /**
     * 开始直播
     *
     * @param view
     */
    public void startLive(View view) {
        mNdkPusher.startLive("rtmp://sendtc3a.douyu.com/live/11546088rU0zRHX7?wsSecret=6888d9705de4cdbc24fe6d70a481aa34&wsTime=64358e78&wsSeek=off&wm=0&tw=0&roirecognition=0&record=flv&origin=tct&txHost=sendtc3a.douyu.com");
    }

    /**
     * 停止直播
     *
     * @param view
     */
    public void stopLive(View view) {
        mNdkPusher.stopLive();
    }

    /**
     * 释放工作
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mNdkPusher.release();
    }
}